package com.fluo;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class ServerConnect extends ListActivity{
		
    static List<String> playList = new ArrayList<String>();
    	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.server);
      
        updateDesktopList();
    }
        
    public void updateDesktopList() {
    	    	
    	ArrayAdapter<String> dServerList = new ArrayAdapter<String>(this,R.layout.song_item,R.id.line1,Login.desktopList);
    	setListAdapter(dServerList);  	
    }
 
    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
    	
    	String DESKTOP_NAME = "";
    	int DESKTOP_PORT = 0;
		Socket socket;
		ObjectInputStream input;
		ObjectOutputStream output;
		
		/////////////////
		// Act on selection
		/////////////////
		String x = Login.desktopList.get(position);
		if(x.equals("Add yourself to a desktop server."))
		{
			Login.desktopList.clear();
	    	startActivity(new Intent(ServerConnect.this, Login.class));	
		}
		else
		{
			String[] words = x.split(":"); // IP:PORT
			DESKTOP_NAME = words[0]; // IP
			String[] words2 = words[1].split("/"); // IP:PORT
			DESKTOP_PORT = Integer.parseInt(words2[0]); // PORT
		
			// Connection Setup
			try {
				socket = new Socket(DESKTOP_NAME, DESKTOP_PORT);

				output = new ObjectOutputStream(socket.getOutputStream());
				input = new ObjectInputStream(socket.getInputStream());
    	
				FluoMessage msg;
		
				// Send desktop server
				msg = new FluoMessage("android");
				output.writeObject(msg);

				// Wait for playlist
				msg = (FluoMessage) input.readObject();
				playList = msg.getDSList();
			
			} catch (UnknownHostException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
			/////////////////////////////////////
			//TESTING             
			playList.add("http://www.alexbednarczyk.com/upload/files/1/05%20Kids.mp3");
			playList.add("http://www.alexbednarczyk.com/upload/files/1/02-tenacious_d-classico.mp3");
			/////////////////////////////////////
		
			//Next
			startActivity(new Intent(ServerConnect.this, FluoPlayer.class));
		}
    }
}
